package com.shinewind.search.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.pojo.doc.ArticleDoc;
import com.shinewind.pojo.dto.PageDto;
import com.shinewind.pojo.entity.Search;
import com.shinewind.pojo.vo.ArticleVo;
import com.shinewind.pojo.vo.PageVo;
import com.shinewind.search.config.resthignlevelclient.properties.RestHignLevelClientProperties;
import com.shinewind.search.mapper.ISearchMapper;
import com.shinewind.search.service.IArticleService;
import com.shinewind.search.service.ISearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl extends ServiceImpl<ISearchMapper, Search> implements ISearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private IArticleService iArticleService;
    @Autowired
    private RestHignLevelClientProperties restHignLevelClientProperties;

    @Override
    public List<Search> getRandomHotList() {
        List<Search> ModelList = RandomUtil.randomEleList(this.list(),3);
        return ModelList;
    }

    @Override
    public PageVo<ArticleDoc> getArticleByKeyword(PageDto pageDto, String keyword) throws IOException {
        //创建搜索对象
        SearchRequest searchRequest = new SearchRequest(restHignLevelClientProperties.getIndexRequest());
        //查询方式
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders
                .multiMatchQuery(keyword,"content","title","name");
        searchRequest.source().query(multiMatchQueryBuilder);
        if(ObjectUtil.isNotNull(pageDto)){
            searchRequest.source().from(pageDto.getCurrentPage() - 1);
            searchRequest.source().size(pageDto.getPageSize());
        }
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //调用客户端查询
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //处理查询结果
        return resolveResponse(searchResponse);
    }
    private PageVo<ArticleDoc> resolveResponse(SearchResponse searchResponse){
        PageVo<ArticleDoc> articleVoPageVo = new PageVo<>();

        SearchHits hits = searchResponse.getHits();
        Long total = hits.getTotalHits().value;
        System.out.println("总条数:"+total);
        articleVoPageVo.setTotal(Math.toIntExact(total));
        if(total > 0){
            SearchHit[] resultHits = hits.getHits();
            List<ArticleDoc> articleDocList = new ArrayList<>();
            if(resultHits != null){
                for(SearchHit doc:resultHits){
                    String sourceAsString = doc.getSourceAsString();
                    ArticleDoc articleDoc = JSON.parseObject(sourceAsString, ArticleDoc.class);
                    articleDocList.add(articleDoc);
                }
                System.out.println("articleDocList:"+articleDocList);
                articleVoPageVo.setData(articleDocList);
                articleVoPageVo.setFlag(true);
                articleVoPageVo.setMessage(messageConstant.SEARCH_SUCCESS);
            }
        }
        else{
            articleVoPageVo.setFlag(false);
            articleVoPageVo.setMessage(messageConstant.SEARCH_ERROR);
        }

        return articleVoPageVo;
    }
}
